package com.hhd.pdf.components.list;

import com.hhd.pdf.CommonUtils;
import com.hhd.pdf.components.AbstractInLineBlockComponent;
import com.hhd.pdf.context.GeneratorContext;
import com.hhd.pdf.variable.ParsedFormula;
import com.hhd.pdf.variable.VariableContext;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import org.dom4j.tree.DefaultElement;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collection;
import java.util.List;

@Component
public class ListComponent extends AbstractInLineBlockComponent {
    @Override
    public List<Element> createElements(org.dom4j.Element element,
                                        GeneratorContext context,
                                        VariableContext rootVariableContext) throws DocumentException, IOException {
        String listFormula = element.attributeValue("list");
        if (CommonUtils.isEmpty(listFormula)) return CommonUtils.newList();

        ParsedFormula formula = ParsedFormula.formula(listFormula);

        List<VariableContext> variableContexts = rootVariableContext.subContextByFormula(formula, false);

        if (CommonUtils.isEmpty(variableContexts)) return CommonUtils.newList();

        List res = CommonUtils.newList();
        for (VariableContext variableContext : variableContexts) {
            res.addAll(createPdfElementsByVariableContext(variableContext, element, context));
        }
        return res;
    }

    @Override
    public void parseComponent(org.dom4j.Element element, GeneratorContext context) throws Exception {
        context.getDocument()
                .addAll(createElements(element, context, context.createRootVariableContext()));
    }

    @Override
    public String getFormula(DefaultElement defaultElement) {
        return defaultElement.attributeValue("list");
    }

    @Override
    public Collection<? extends Element> createPdfElement(DefaultElement defaultElement,
                                                          GeneratorContext context,
                                                          String parsedFormula) throws DocumentException, IOException {
        return createElements(defaultElement, context, context.createRootVariableContext());
    }

    @Override
    public String getName() {
        return "list";
    }
}
